<template>
  <!-- 设备信息表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    style="min-width: 600px; max-width: 800px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="equipCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipCode"
              placeholder="请输入设备编号"
              clearable
            />
            <span v-else>{{ formData.equipCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="equipName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipName"
              placeholder="请输入设备名称"
              clearable
            />
            <span v-else>{{ formData.equipName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="equipModel">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipModel"
              placeholder="请输入设备型号"
              clearable
            />
            <span v-else>{{ formData.equipModel }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="equipTypeName">
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请输入设备类型"
              style="width: 300px"
              filterable
              v-model="formData.equipTypeId"
              :data="mdmequiptypeTree"
              node-key="id"
              clearable
              @node-click="handleEquipTypeNameClick"
              :props="{ label: 'equipTypeName', children: 'nodes' }"
              check-strictly
              :render-after-expand="false"
            />
            <span v-else>{{ formData.equipTypeName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备状态" prop="equipStatusName">
            <el-select
              v-if="!props.isReadonly"
              v-model="formData.equipStatus"
              placeholder="请输入设备状态"
              style="width: 300px"
              clearable
              @change="equipStatusHandler"
            >
              <el-option
                v-for="item in equipStatusTree"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-else>{{ formData.equipStatusName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="位置" prop="locationId">
            <el-tree-select
              v-if="!props.isReadonly"
              placeholder="请输入位置"
              style="width: 300px"
              filterable
              v-model="formData.locationId"
              :data="locationInfoTree"
              node-key="id"
              clearable
              :props="{ label: 'locationName', children: 'nodes' }"
              check-strictly
              :render-after-expand="false"
            />
            <span v-else>{{ formData.allName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="资产编码" prop="assetCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.assetCode"
              placeholder="请输入资产编码"
              clearable
            />
            <span v-else>{{ formData.assetCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" v-if="!props.isReadonly">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
            <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              type="textarea"
              :maxlength="255"
              show-word-limit
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />
            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="props.isReadonly">
        <el-col :span="12">
          <el-form-item label="创建时间" prop="createTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createTime"
              placeholder="请输入创建时间"
              clearable
            />
            <span v-else>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建人" prop="createdUserName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.createdUserName"
              placeholder="请输入创建人"
              clearable
            />
            <span v-else>{{ formData.createdUserName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="props.isReadonly">
        <el-col :span="12">
          <el-form-item label="修改时间" prop="lastUpdateTime">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdateTime"
              placeholder="请输入修改时间"
              clearable
            />
            <span v-else>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="修改人" prop="lastUpdatedUserName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.lastUpdatedUserName"
              placeholder="请输入修改人"
              clearable
            />
            <span v-else>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMMDMEQUIPINFOADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  equipCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入设备编号",
      trigger: "blur",
    },
  ],
  equipName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入设备名称",
      trigger: "blur",
    },
  ],
  equipModel: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入设备型号",
      trigger: "blur",
    },
  ],
  equipTypeName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入设备类型",
      trigger: "blur",
    },
  ],
  equipStatusName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入设备状态",
      trigger: "blur",
    },
  ],
  locationId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入位置",
      trigger: "blur",
    },
  ],
  assetCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
    {
      required: true,
      message: "请输入资产编码",
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  allName: "",
  equipCode: "",
  equipName: "",
  equipModel: "",
  equipLargeCategory: "",
  equipTypeId: "",
  equipTypeCode: "",
  equipTypeName: "",
  equipStatus: "",
  equipStatusName: "",
  locationId: "",
  assetCode: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        allName,
        equipCode,
        equipName,
        equipModel,
        equipLargeCategory,
        equipTypeId,
        equipTypeCode,
        equipTypeName,
        equipStatus,
        equipStatusName,
        locationId,
        assetCode,
        organizationId,
        organizationCode,
        organizationName,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        allName,
        equipCode,
        equipName,
        equipModel,
        equipLargeCategory,
        equipTypeId,
        equipTypeCode,
        equipTypeName,
        equipStatus,
        equipStatusName,
        locationId,
        assetCode,
        organizationId,
        organizationCode,
        organizationName,
        enabled,
        deleted,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.allName = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.equipModel = "";
  formData.equipLargeCategory = "";
  formData.equipTypeId = "";
  formData.equipTypeCode = "";
  formData.equipTypeName = "";
  formData.equipStatus = "";
  formData.equipStatusName = "";
  formData.locationId = "";
  formData.assetCode = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/mdm/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 获取设备类型下拉树
const mdmequiptypeTree = ref([]);
const getMdmequiptypeTree = async () => {
  const { data } = await request({
    url: "/mdm/mdmequiptype/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  mdmequiptypeTree.value = data;
};

// 设备类型选择
const handleEquipTypeNameClick = (node: any) => {
  formData.equipTypeName = node.equipTypeName;
  formData.equipTypeCode = node.equipTypeCode;
  console.log(node);
};

const loading = ref(false);

/** 设备信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmequipinfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

const equipStatusTree = ref([]);
const equipStatusHandler = (value: any) => {
  equipStatusTree.value.forEach((item: any) => {
    if (item.value == value) {
      formData.equipStatusName = item.label;
    }
  });
};

onMounted(async () => {
  await Promise.all([getLocationInfoTree(), getMdmequiptypeTree()]);
  equipStatusTree.value = useDictionary("EquipStatus");
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
